<template>
	<md-field-group class="register_submit">
		<md-field v-model="code" icon="mobile" placeholder="请输入验证码">
			<div slot="rightIcon" @click="getCode" class="getCode red">
				<countdown v-if="counting" :time="60000" @end="countdownend">
				  <template slot-scope="props">{{ +props.seconds || 60 }}秒后获取</template>
				</countdown>
				<span v-else>获取验证码</span>
			</div>
		</md-field>
		<md-field v-model="password" icon="lock" placeholder="请输入密码"/>
		<md-field v-model="repeatPassword" icon="lock" placeholder="请再次确认密码"/>

		<div class="register_submit_btn">
			<van-button type="danger" size="large" @click="registerSubmit">确定</van-button>
		</div>
	</md-field-group>
</template>

<script>
	import {authRegisterCaptcha,authRegister} from '@/api/api';

	import field from '@/components/field/';
	import fieldGroup from '@/components/field-group/';

	let mobile;
	export default {
		data() {
			return {
				counting: false,
				code: '',
				password: '',
				repeatPassword: ''
			};
		},
		created() {
			mobile = this.$route.query.mobile;
			this.getCode();
		},
		methods: {
			registerSubmit() {
				if(this.validate()){
					authRegister({
						username: mobile,
						mobile: mobile,
						code: this.code,
						password: this.password
					}).then(() => {
						this.$router.push({
							name: 'registerStatus',
							params: {status: 'success'}
						});
					}).catch(error => {
						this.$toast.fail(error.data.errmsg);
					});
				}else{
					this.$toast.fail("输入密码不一致");
				}
			},
			getCode() {
				if (!this.counting) {
					authRegisterCaptcha({
						mobile: mobile
					}).then(() => {
						this.$toast.success('发送成功');
						this.counting = true;
					}).catch(error => {
						this.$toast.fail(error.data.errmsg);
						this.counting = false;
					})
				}
			},
			validate(){
				if(!this.code){
					this.$toast.fail("验证码必须填写");
					return false;
				}

				if(!this.password){
					this.$toast.fail("密码必须填写");
					return false;
				}

				if(!this.repeatPassword){
					this.$toast.fail("重复密码必须填写");
					return false;
				}

				if(this.password !== this.repeatPassword){
					this.$toast.fail("两次输入密码不一致");
					return false;
				}

				return true;
			},
			countdownend() {
				this.counting = false;
			}
		},

		components: {
			[field.name]: field,
			[fieldGroup.name]: fieldGroup
		}
	};
</script>


<style lang="scss" scoped>
@import '../../../assets/scss/mixin';

.register_submit {
  padding-top: 40px;
  background-color: #fff;
}

.register_submit_btn {
  padding-top: 30px;
}

.getCode {
  @include one-border(left);
  text-align: center;
}

.time_down {
  color: $red;
}
</style>
